<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <!-- <div class="head-container">
          <el-input
            v-model="treeName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container tree-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['31510']"
              @click="handleAddclass"
              >添加分类</el-button
            >
          </el-col>
          <!-- <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar> -->
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column
            label="分类名称"
            prop="curriculumClassification"
            align="center"
          >
            <template slot-scope="scope">
              <span @click="handleAdd(scope.row)" class="active">{{
                scope.row.curriculumClassification
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="课程数量"
            prop="curriculumNum"
            align="center"
          />
          <!-- <el-table-column label="分类简介" prop="titleName" align="center" /> -->
          <!-- <el-table-column label="顺序号" prop="titleName" align="center" /> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <!-- <el-button
                  size="mini"
                  type="text"
                  v-hasPermi="['31520']"
                  @click="handleUpdate(scope.row)"
                >修改</el-button> -->
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['31530']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pagesize"
          @pagination="getList"
        />
        <!-- 添加或修改角色配置对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open1"
          width="500px"
          append-to-body
        >
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            :validate-on-rule-change="false"
            label-width="80px"
          >
            <el-form-item label="岗位" prop="postId">
              <treeselect
                v-model="form.postId"
                :options="treeOptions"
                :show-count="true"
                placeholder="请选择岗位"
                @select="selectTree"
              />
            </el-form-item>
            <el-form-item label="课程分类" prop="curriculumClassificationId">
              <el-select
                v-model="form.curriculumClassificationId"
                placeholder="请选择"
                @change="changeHier"
              >
                <el-option
                  v-for="item in classOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 分类名称 弹框 -->
        <el-dialog
          width="767px"
          :visible.sync="open"
          :title="title"
          append-to-body
        >
          <el-table
            v-loading="loading"
            :data="questionList"
            :border="true"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="课程名称"
              prop="title"
              align="center"
              :show-overflow-tooltip="true"
              width="160"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="introduce"
              label="课程介绍"
              width="200"
            />
            <el-table-column
              align="center"
              prop="classHours"
              label="培训课时"
              width="160"
            />
            <el-table-column
              label="课程类型"
              prop="classification"
              align="center"
              width="150"
            ></el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.currentPage"
            :limit.sync="queryParams.pagesize"
            @pagination="getList"
          />
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm1">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getInstitutions, getDepartment, getDict } from "@/api/select";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import {
  getPage,
  listData,
  Single,
  getData,
  delData,
  addData,
  updateData,
  Coursepopup,
} from "@/api/trainAdmin/trainMatrix";

export default {
  name: "trainMatrix",
  components: { Treeselect },
  data() {
    return {
      activeName: "first",
      treeName: undefined,
      // 设置课程并完成发布 参数
      releaseParams: {},

      treeOptions: [], //  树级
      questionList: [], //  分类名称弹框
      classOptions: [], //  课程分类下拉
      currentId: null,
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        postId: undefined,
        keywords: undefined,
        category: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      open1: false,
      form: {},
      rules: {
        postId: [
          { required: true, message: "请选择上级类别", trigger: "change" },
        ],
        curriculumClassificationId: [
          { required: true, message: "请选择上级类别", trigger: "change" },
        ],
      },
      statusOptions: [],
    };
  },
  computed: {},
  watch: {
    // 根据名称筛选树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // 获取数据字典
    getDict(17, 0).then((response) => {
      //17-课程分类
      this.classOptions = response.result.data;
    });

    this.getPageInfo();
  },
  methods: {
    // 数组去重
    unique(arr) {
      // 利用对象访问属性的方法，判断对象中是否存在key
      var result = [];
      var obj = {};
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i].theid]) {
          result.push(arr[i]);
          obj[arr[i].theid] = true;
        }
      }
      return result;
    },
    getPageInfo() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data;
        if (this.currentId === null) {
          //首次进入当前页面
          this.currentId = response.result.data[0].id; //将节点id赋值给上级id
        }
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        // this.defaultExpandkeys[0] = this.currentId;
        this.getList();
      });
    },
    getList() {
      this.loading = true;
      console.log(this.currentId);
      this.queryParams.postId = this.currentId;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.currentId = data.id; //id
      // this.defaultExpandkeys[0] = this.currentId;   //下一次获取树，默认展开的节点
      this.getList();
    },
    // handleQuery() {
    //   this.queryParams.currentPage = 1;
    //   this.getList();
    // },
    // resetQuery() {
    //   this.resetForm("queryForm");
    //   this.handleQuery();
    // },
    handleAdd(row) {
      console.log("课程", row);
      this.releaseParams.theid = row.theid;
      console.log(this.releaseParams.theid);
      this.reset();
      // this.queryParams.category = row.theid;
      Single(this.queryParams).then((response) => {
        let arr = this.questionList.concat(response.result.rows);
        this.crewOptions = this.unique(arr);
        // console.log(response);
        // this.total = response.result.total;
        // this.loading = false;
      });
      this.open = true;
      this.title = "选择";
    },
    handleAddclass() {
      this.reset();
      this.open1 = true;
      this.title = "添加";
    },
    // handleUpdate(row) {
    //   this.reset();
    //   const theId = row.id;
    //   getData(theId).then((response) => {
    //     this.form = response.result;
    //     // this.form.dictId = this.currentId
    //     this.open = true;
    //     this.title = "修改";
    //   });
    // },
    submitForm1() {
      // this.resetRelease();
      let _this = this;
      if (this.questionList.length > 0) {
        let idArr = [];

        this.questionList.forEach((item) => {
          idArr.push(item.theid);
        });
        this.releaseParams.curriculumIds = idArr.join(","); //消息接收人员名单id列表
      }
      console.log(this.releaseParams);
    },
    resetRelease() {
      this.releaseParams = {
        theid: undefined, //id
        postId: undefined, //岗位 id
        post: undefined, //岗位
        // curriculumClassificationId: val.curriculumClassificationId, //课程分类id
        // curriculumClassification: val.curriculumClassification, //课程分类
        curriculumIds: undefined,
      };
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open1 = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open1 = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        postId: this.currentId,
        titleName: undefined,
        category: undefined,
        curriculumClassificationId: undefined,
        sort: 0,
        theid: undefined,
      };
      this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const theId = row.theid;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.theid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    changeHier(val) {
      if (this.classOptions.length > 0) {
        this.form.curriculumClassification = val
          ? this.classOptions.find((ele) => ele.id === val).label
          : "";
      }
    },
    selectTree(val) {
      if (this.treeOptions.length > 0) {
        this.form.post = val.label;
      }
    },
  },
};
</script>

<style scoped lang="scss">
/deep/ .el-tabs__item {
  font-size: 16px;
}
/* treeselect */
.vue-treeselect__input {
  display: block;
}
/deep/ .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
  margin-top: 3px;
}
.add-person /deep/ .el-dialog__body {
  min-height: 240px;
}
</style>